package com.springboot.mongodb.impl;

import com.springboot.mongodb.dao.UserDao;
import com.springboot.mongodb.model.AddUserDTO;
import com.springboot.mongodb.model.FindUserDTO;
import com.springboot.mongodb.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @ClassName springboot_mongodb - UserServiceImpl
 * @Description [此类用于: ]
 * @Author liming-jybdd@foxmail.com
 * @Date 2021/9/2614:41
 * @Version 1.0
 **/
@Service
public class UserServiceImpl {

    @Autowired
    private UserDao userdao;

    public User addUser(AddUserDTO addUserDTO){
        User user = new User();
        user.setName(addUserDTO.getName());
        user.setAge(addUserDTO.getAge());
        user.setGender(addUserDTO.getGender());
        user.setLabel(addUserDTO.getLabel());
        user.setRating(addUserDTO.getRating());
        user.setSize(addUserDTO.getSize());
        return userdao.insert(user);
    }

    public Page<User> findAll(FindUserDTO findUserDTO) {

        Pageable pageable = PageRequest.of(findUserDTO.getPage() - 1, 2);
        return userdao.findAll(pageable);
    }

    public User findByName(FindUserDTO findUserDTO) {
        return userdao.findByName(findUserDTO.getName());
    }

    public boolean del(User user) {
        userdao.deleteById(user.getId());
        return true;
    }

    public User upd(User user) {
        Optional<User> user1 = userdao.findById(user.getId());
        if (user.getAge() == null) {
            user.setAge(user1.get().getAge());
        }
        if (user.getName() == null) {
            user.setName(user1.get().getName());
        }
        if (user.getGender() == null) {
            user.setGender(user1.get().getGender());
        }
        if (user.getLabel() == null) {
            user.setLabel(user1.get().getLabel());
        }

        //save是属于替换，
        User save = userdao.save(user);
        return save;
    }

}